package com.example.icampusevent;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.icampusevent.jsonobjects.Invitation;
import com.example.icampusevent.jsonobjects.ReturnStatus;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MessageListAdapter extends BaseAdapter {
	
	private Activity activity = null;
	private ArrayList<Invitation> invitationList = null;
	
	public MessageListAdapter(Activity _activity, ArrayList<Invitation> _invitationList) {
		activity = _activity;
		invitationList = _invitationList;
	}

	public int getCount() {
		return invitationList.size();
	}

	public Object getItem(int position) {
		return null;
	}

	public long getItemId(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View vi = convertView;
		if(convertView==null) {
			LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			vi = inflater.inflate(R.layout.message_list_row_layout, null);
		}
		
		TextView friendName = (TextView)vi.findViewById(R.id.friend_name);
		friendName.setText(invitationList.get(position).getFirstname() +
				" " + invitationList.get(position).getLastname());
		TextView eventTitle = (TextView)vi.findViewById(R.id.event_title);
		eventTitle.setText(invitationList.get(position).getTitle());
		
		final int p = position;
		Button acceptButton = (Button)(vi.findViewById(R.id.accept_button));
		acceptButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				removeInvitation(p);
				// navigate user to event detail
				Intent intent = new Intent(activity, EventDetailActivity.class);
				intent.putExtra("EVENTID", invitationList.get(p).getEventid());
				intent.putExtra("USERID", ((MessageActivity)activity).getUserId());
				activity.startActivity(intent);
			}
		});
		
		Button ignoreButton = (Button)(vi.findViewById(R.id.ignore_button));
		ignoreButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				removeInvitation(p);
			}
		});
		
		return vi;
	}
	
	
	private void removeInvitation(int position) {
		Long alertId = invitationList.get(position).getAlertid();
		String url = "http://hamedaan.usc.edu:8080/team15/AlertServlet?q=remove&alertid=" + alertId;
		RemoveInvitationTask task = new RemoveInvitationTask();
		task.execute(url);
	}
	
	
	private class RemoveInvitationTask extends AsyncTask<String, Integer, Reader> {
	     protected Reader doInBackground(String... url) {
	    	 InputStream source = retrieveStream(url[0]);
	 		 if(source == null) return null;
	 		 
	 		 Reader inputReader = new InputStreamReader(source);
	 		 return inputReader;
	     }

	     protected void onPostExecute(Reader json) {
	 		 Gson gson = new Gson();
			 ReturnStatus status = gson.fromJson(json, ReturnStatus.class);
		     if(status.getStatus().equals("error")) {
		    	 toast("Error: cannot remove the invitation.");
		     }
	     }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		
	 		return null;
	 	}
	}
	
	
	public void toast(String s) {
		CharSequence text = s;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(activity, text, duration);
		toast.show();
	}

}
